package org.xtframe.service.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jbpm.api.Execution;
import org.jbpm.api.task.Task;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.xtframe.entity.UserData;
import org.xtframe.service.AjaxDataHandler;
import org.xtframe.service.AjaxDataHandlerException;
import org.xtframe.util.CommonUtil;
import org.xtframe.util.ContextUtil;
import org.xtframe.util.JbpmUtil;
import org.xtframe.util.WorkflowUtil;

@Service
@Scope("prototype")
public class CompleteTaskDataHandler implements AjaxDataHandler {

	private final Log logger = LogFactory.getLog(getClass());

	@SuppressWarnings("rawtypes")
	public Map<String, Object> execute(String strData) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		try {
			UserData userData = ContextUtil.getCurrentUserData();
			if(userData == null){
				map.put(STATUS, false);
				map.put(LOGIN, true);
				throw new AjaxDataHandlerException("未登陆完成任务", 1);
			}
			
			Map<String, Object> variables = null;
			String outcome = null;
			JSONObject objJson = JSONObject.fromObject(strData);
			if(!(objJson.has("taskId") && objJson.has("pageId") && objJson.has("opinion"))) 
				throw new AjaxDataHandlerException("完成任务参数不正确");
			
			String taskId = objJson.optString("taskId");
			String pageId = objJson.optString("pageId");
			if(objJson.has("variables")){
				JSONObject variablesJson = objJson.getJSONObject("variables");
				if(variablesJson != null){
					variables = new HashMap<String, Object>();
					Iterator it = variablesJson.keys();
		            while (it.hasNext()) {
		                String key = (String)it.next();
		                variables.put(key, variablesJson.getString(key));
		            }
				}
			}
			if(objJson.has("outcome")){
				outcome = objJson.optString("outcome", null);
			}
			String opinion = objJson.optString("opinion");
			
			String recordId = CommonUtil.getUUID();
			Task task = JbpmUtil.getInstance().getTaskService().getTask(taskId);
			Execution execution = JbpmUtil.getInstance().getExecutionService().findExecutionById(task.getExecutionId());
			String processInstanceId = execution.getProcessInstance().getId();
			String subject = JbpmUtil.getInstance().getTaskByTaskId(taskId).getName() + " [" + userData.getUser().getUserName()+"]";
			String time = CommonUtil.getCurrentTime();
			
			// 存入任务相关记录
			if(WorkflowUtil.saveTaskRecord(recordId, processInstanceId, taskId, 
					userData.getUser().getUserId(), subject, opinion, outcome==null?"":outcome, time, pageId)) {
				try {
					// 进行任务完成操作
					if(variables != null){
						JbpmUtil.getInstance().setVariables(taskId, variables);
					}
					JbpmUtil.getInstance().completeTask(taskId, outcome);
					
					try {
						// 判断是否流程结束
						// 流程结束进行标记位设置
						if(JbpmUtil.getInstance().isProcessInstanceEnd(processInstanceId)){
							WorkflowUtil.stopProcess(processInstanceId, time);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					
					map.put(STATUS, true);
				} catch (Exception e) {
					WorkflowUtil.deleteTaskRecord(recordId);
					throw e;
				}
			} else {
				map.put(STATUS, false);
			}
		} catch(AjaxDataHandlerException ex){
			logger.warn(ex.toString());
			if(ex.getFlag() == 0){
				map.clear();
				map.put(STATUS, false);
			}
		} catch (Exception e) {
			logger.error(e.toString());
			map.clear();
			map.put(STATUS, false);
		}
		
		return map;
	}

}
